package com.weiyan.blog.sucurity;

import com.alibaba.fastjson.JSON;
import com.weiyan.blog.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author misterWei
 * @create 2020年01月20号:18点15分
 * @mailbox mynameisweiyan@gmail.com
 */
//自定义用户管理器
@Component
public class UserServerAuth implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        //将当前登陆用户的信息存储到安全服务器管理中心
        com.weiyan.blog.entity.User user = userRepository.findByEmail(email);
        if (user == null) return  null;
        List<String> perLists = new ArrayList();
        if (!user.getRoles().isEmpty()){
           user.getRoles().forEach(role -> {
               if (!role.getPermissions().isEmpty()){
                   role.getPermissions().forEach(permission -> {
                       perLists.add(permission.getCode());
                   });
               }
           });
       }

        if (email.equals(user.getEmail())){
            // 清空文章信息 此处为冗余数据
            user.setArticles(null);
            return User.builder().username(JSON.toJSONString(user)).password(user.getPassword()).authorities(perLists.toArray(new String[perLists.size()])).build();
          }
        return null;


    }

}
